import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from '@vant/auto-import-resolver';
import { visualizer } from 'rollup-plugin-visualizer';

const path = require('path');
const pathSrc = path.resolve(__dirname, 'src');

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
    const { VITE_APP_BASE_URL, VITE_APP_BASE_PRE } = loadEnv(mode, process.cwd());

    return {
    // Static Resource Base Path base: './' || '',
        base: process.env.NODE_ENV === 'production' ? './' : '/',
        resolve: {
            alias: {
                '@': path.resolve(__dirname, 'src'),
                pinia: path.resolve(__dirname, './node_modules/pinia'),
                '@TUIRoom': path.resolve(__dirname, 'src/TUIRoom'),
            },
        },
        build: {
            rollupOptions: {
                output: {
                // Custom Split Strategy
                    manualChunks: {
                        roomEngine: ['@tencentcloud/tuiroom-engine-js'],
                        roomkit: ['@tencentcloud/roomkit-web-vue3'],
                    },
                },
            },
        },
        plugins: [
            vue({
            // Explanation: Solved the problem of introducing the generation of userSig files.
            // reactivityTransform: true,
            }),
            visualizer({
            // open: true,
            }),
            AutoImport({
                imports: ['vue', '@vueuse/core'],
                resolvers: [VantResolver()],
                vueTemplate: true, // 是否在 vue 模板中自动导入
                dts: path.resolve(pathSrc, 'types', 'auto-imports.d.ts'), //  自动导入组件类型声明文件位置，默认根目录; false 关闭自动生成
            }),
            Components({
                resolvers: [VantResolver()],
                dts: path.resolve(pathSrc, 'types', 'components.d.ts'), //  自动导入组件类型声明文件位置，默认根目录; false 关闭自动生成
            }),
        ],
        server: {
            open: true,
            // Solve the problem of infinite page refresh after whistle proxy
            // hmr: {
            //     protocol: 'ws',
            //     host: '127.0.0.1',
            // },
            hmr: true,
            proxy: {
                [VITE_APP_BASE_PRE]: {
                    target: VITE_APP_BASE_URL,
                    ws: true,
                    changeOrigin: true,
                    rewrite: path => path.replace(new RegExp(`^${VITE_APP_BASE_PRE}`), ''),
                },
            },
        },
        optimizeDeps: {
            include: [
                'vue',
                'vue-router',
                'pinia',
                'axios',
                '@vueuse/core',
            ],
        },
    };
});
